package use.thread.sync.cooperation;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AwaitSignalExample {
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void before() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getId());
            condition.signalAll();
            System.out.println("before");
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getId());
        }
    }

    public void after() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getId());
            condition.await();
            System.out.println("after");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getId());
        }
    }

    public static void main(String[] args) {
        AwaitSignalExample awaitSignalExample = new AwaitSignalExample();
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute( () -> {
                awaitSignalExample.after();
            });
        }

        executorService.execute( () -> {
            awaitSignalExample.before();
        });
    }
}
